package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "sync"
    "time"
	"sync/atomic"
)

// 定义全局变量用于统计请求相关数据
var (
    totalRequests    int32    // 总请求数
    successfulRequests int32    // 成功请求数
    failedRequests   int32    // 失败请求数
    startTime        time.Time
    endTime          time.Time
)

func main() {
    var wg sync.WaitGroup
    concurrency := int32(500) // 将concurrency声明为int32类型
    totalRequests = int32(10000) // 总请求数，也可以按需调整

    // 记录开始时间
    startTime = time.Now()

	i := int32(0)
    for ; i < concurrency; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
			j := int32(0)
            for ; j < totalRequests / concurrency; j++ {
                resp, err := http.Get("http://localhost:8888/ping")
                if err!= nil {
                    fmt.Println("请求出错:", err)
                    atomic.AddInt32(&failedRequests, 1)
                    continue
                }
                defer resp.Body.Close()
                _, err = ioutil.ReadAll(resp.Body)
                if err!= nil {
                    fmt.Println("读取响应出错:", err)
                    atomic.AddInt32(&failedRequests, 1)
                    continue
                }
                atomic.AddInt32(&successfulRequests, 1)
            }
        }()
    }

    wg.Wait()

    // 记录结束时间
    endTime = time.Now()
    elapsedTime := endTime.Sub(startTime).Seconds()
    qps := float64(successfulRequests) / elapsedTime
    fmt.Printf("总请求数: %d\n", totalRequests)
    fmt.Printf("成功请求数: %d\n", successfulRequests)
    fmt.Printf("失败请求数: %d\n", failedRequests)
    fmt.Printf("QPS: %.2f\n", qps)
}